import Vue from 'vue'
import Vuex from 'vuex'

import createPersistedState from "vuex-persistedstate"

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState({
    storage: window.sessionStorage
  })],
  state: {
    xmItem: {},
    gzItem: {},

    // yhxx: null,
    xtInfo: {},
    fnList: [],
    stTree: [],
    stTreeObj: {},
    gsList: [],
    mxstgxList: [],
  },
  mutations: {
    // fn
    setFnList(state, fnList) {
      state.fnList = fnList
    },
    // gs
    setGsList(state, gsList) {
      state.gsList = gsList
    },
    // st
    setStTree(state, stTree) {
      state.stTree = stTree
    },
    setStTreeObj(state, stTreeObj) {
      state.stTreeObj = stTreeObj
    },
    // xt
    setXtInfo(state, xtInfo) {
      state.xtInfo = xtInfo
    },
    // mxstgx
    setMxstgxList(state, mxstgxList) {
      state.mxstgxList = mxstgxList
    },

  },
  actions: {
    async initDesignData() {
      await this.dispatch("loadFnList")

      await this.dispatch("loadGsList")

      await this.dispatch("loadStTree")
    },
    async loadStTree({commit}) {
      let xmItem = mySessionStorage.getItem("xm-item", {})
      let stTree = await Vue.prototype.$api.queryStTree({xmbm: xmItem.xmbm})

      let stTreeObj = {}
      stTree.forEach(stdy => {
        stdy.stjg.forEach(stjg => {
          let zdmc = `${stdy.stbm}.${stjg.zdmc}`
          stTreeObj[zdmc] = {
            zdmc,
            zdzwmc: `${stdy.stmc}.${stjg.zdms}`,
            kjlx: stjg.zdlx,
            sjybm: stjg.sjybm,
            glcs: stjg.glcs,
            sjydz: stjg.sjydz,
          }
        })
      })
      commit('setStTreeObj', stTreeObj)

      stTree = stTree.map(item => {
        return {
          ...item,
          label: item.stmc,
          value: item.stbm,
          id: item.stdybm,
          children: item.stjg.map(_item => {
            return {
              ..._item,
              label: _item.zdms,
              value: _item.zdmc,
              id: _item.stjgbm,
              parent: item
            }
          })
        }
      })

      commit('setStTree', stTree)
    },
    async loadFnList({commit}) {
      let fnList = await Vue.prototype.$api.getFnList()
      fnList.sort((a, b) => {
        if (a.builtIn && !b.builtIn) return -1;
        if (b.builtIn && !a.builtIn) return 1;
        return 0
      })
      commit('setFnList', fnList)
    },
    async loadGsList({commit}) {
      let gsList = await Vue.prototype.$api.getGsList()
      commit('setGsList', gsList)
    },
    async loadMxstgxList({commit}) {
      let xmItem = mySessionStorage.getItem("xm-item", {})
      let res = await Vue.prototype.$api.queryMxstgxListByXmbm({xmbm: xmItem.xmbm})
      commit("setMxstgxList", res)
    }
  },
  modules: {},
  getters: {}
})
